package com.tang.sharding.algorithm.standard;

import com.tang.sharding.algorithm.AbstractDateShardingAlgorithm;
import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.api.algorithm.sharding.RangeShardingValue;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Set;
import java.util.StringJoiner;

/**
 * @author Tang
 * @classname DayShardingAlgorithm
 * @description [ 天策略 ]
 * @date 2021/7/30 10:25
 */
public class DayShardingAlgorithm extends AbstractDateShardingAlgorithm {

    @Override
    public String doPreciseSharding(PreciseShardingValue<Date> shardingValue) {
        LocalDateTime dateTime = LocalDateTime.from(shardingValue.getValue().toInstant().atZone(ZoneId.systemDefault()));
        StringJoiner stringJoiner = new StringJoiner("_");
        stringJoiner.add(shardingValue.getLogicTableName());
        stringJoiner.add((String.valueOf(dateTime.getYear())));
        stringJoiner.add((String.valueOf(dateTime.getMonthValue())));
        stringJoiner.add((String.valueOf(dateTime.getDayOfMonth())));
        return stringJoiner.toString();
    }

    @Override
    protected void doDateRangeSharding(Set<String> tableNamesSet,
                                       RangeShardingValue<Date> shardingValue,
                                       LocalDateTime t1, LocalDateTime t2) {
        while (t1.isBefore(t2) || (t1.compareTo(t2) == 0)) {
            StringJoiner stringJoiner = new StringJoiner("_");
            stringJoiner.add(shardingValue.getLogicTableName());
            stringJoiner.add((String.valueOf(t1.getYear())));
            stringJoiner.add((String.valueOf(t1.getMonthValue())));
            stringJoiner.add((String.valueOf(t1.getDayOfMonth())));
            tableNamesSet.add(stringJoiner.toString());
            t1 = t1.plusDays(1);
        }
    }
}